package com.lbt.weixin.server.common;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.lbt.framework.exception.MyException;

import weixin.popular.api.TokenAPI;
import weixin.popular.bean.token.Token;

public abstract class WeixinUtil {

	private static Map<String, String> tokenInfo = new HashMap<String, String>();
	
	static {
		tokenInfo.put("expire_time", "0");
		getAccessToken();
	}
	
	public static String getAccessToken() {
		long timestamp = Long.parseLong(tokenInfo.get("expire_time"));
		if (timestamp < new Date().getTime()) {
			WeixinAppConfig config = WeixinAppConfig.getInstance();
			Token token = TokenAPI.token(config.getAppId(), config.getAppSecret());
			if (!token.isSuccess()) {
				throw new MyException(Integer.parseInt(token.getErrcode()), token.getErrmsg());
			}
			
			tokenInfo.put("expire_time", ""  + (token.getExpires_in()*1000 + new Date().getTime()));
			tokenInfo.put("access_token", token.getAccess_token());
		}
		return tokenInfo.get("access_token");
	}
}
